<template>
<MenuPage
  :columns="testPaperCol"
  :data="testPaperList"
  :page.sync="query.pageIndex"
  :size.sync="query.pageSize"
  :total="testPaperListTotal"
  :loading="tableLoading"
  @queryFun="queryTestPaperList">
  <template slot="search">
   
      <Checkbox v-model="createByMe" @on-change="changePage(1)">由我创建</Checkbox>
      <Select filterable v-model="testPaper.type" style="width:150px;margin-left: 15px" clearable placeholder="自测" @on-change="changePage(1)">
        <Option value="self">是</Option>
        <Option value="teach">否</Option>
      </Select>
      <i-select clearable placeholder="可见范围" style="width: 150px;margin-left: 15px" v-model="testPaper.visibility" @on-change="changePage(1)">
        <i-option value="public">系统</i-option>
        <i-option value="share">单位</i-option>
        <i-option value="private">个人</i-option>
      </i-select>
      <Select filterable v-model="testPaper.advanced" style="width:150px;margin-left: 15px" clearable placeholder="进阶考试" @on-change="changePage(1)">
        <Option value="1">是</Option>
        <Option value="0">否</Option>
      </Select>
      <Select filterable v-model="testPaper.difficulty" style="width:150px;margin-left: 15px" clearable placeholder="难度" @on-change="changePage(1)">
        <Option value="simple">简单</Option>
        <Option value="medium">中等</Option>
        <Option value="hard">较难</Option>
      </Select>
      <Input v-model.trim="testPaper.paperName" clearable placeholder="试卷名称" style="width: 180px;margin-left: 15px" @on-change="changePage(1)" />
    
       <Button type="primary" ghost @click="addTestPaper($event,'add')" class="md-add-jh"
       style="margin-left: 15px"><i class="el-icon-edit"></i>创建</Button>
    
    
      <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshTestPaperList()"><i class="el-icon-refresh-right" /></Button>
  </template>
  <Modal v-model="previewModal.show" :title="previewModal.title" :width="1000" id="previewModal" class-name="vertical-center-modal"  :mask-closable="false">
    <div  ref="pdf" style="padding:30px">
      <h2 style="margin: 0 auto;text-align: center;margin-bottom: 20px">{{this.paperName}}</h2>
      <QuestionList :data="preQuestionList" :showWriteUp="true" :showGrade="false"></QuestionList>
    </div>
    <div slot="footer">
      <Button @click="handleExport" type="primary" >下载pdf</Button>
    </div>
  </Modal>
</MenuPage>
</template>
<script>
import { downloadPDF } from '@/libs/pdf.js';
import usally from '@/mixin/usally';
import { delTestPaper, queryTestPaperList, queryTestPaperQuestionList,paperGetUsedTimes } from '@/api/testpaper';
import encryption from '@/libs/encryption.js';
import { debounce } from '@/libs/utils';
import QuestionList from '@/components/question-list';
import pageTitle from '@/mixin/pageTitle';
export default {
  mixins: [usally,pageTitle],
  components: {
    QuestionList
  },
  data() {
    const validateName = (rule, value, callback) => {
      //验证只能填入数字
      var reg = new RegExp('^[\u4E00-\u9FA5a-zA-Z0-9_-]*$');
      //验证警戒值
      if (value) {
        if (!reg.test(value)) {
          callback(new Error('请输入中文、数字、字母、下划线、-'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    let September = sessionStorage.getItem('November');
    September = JSON.parse(encryption.SelfUseDecrypt(September));
    return {
      paperName: '',
      USER_ID: September.userId,
      USER_Name: September.nickname,
      isRootDesigner: September.isRootDesigner,
      showDefImg: true,
      showDefText: '加载中',
      previewModal: {
        //预览modal
        show: false,
        title: '预览',
        loading: false
      },
      query: {
        pageIndex: 1,
        pageSize: 10
      },
      testPaper: {
        paperName: '',
        visibility: '',
        type: '',
        difficulty: '',
        advanced: ''
      },
      testPaperCol: [
        //        {
        //          type: 'index',
        //          width: 60,
        //          align: 'center',
        //          tooltip: true
        //        },
        {
          title: '名称',
          key: 'paperName',
          tooltip: true,
          placement: 'top-left',
          width: 400,
          minWidth:100,
        },
        {
          title: '难度',
          key: 'difficulty',
          minWidth:50,
          render: (h, params) => {
            return h('span', this.$options.filters.difficultyFilter(params.row.difficulty));
          }
        },
        {
          title: '可见范围',
          key: 'visibility',
          minWidth:50,
          render: (h, params) => {
            let text = '';
            let color = '';
            if (params.row.visibility === 'share' || params.row.visibility === '1') {
              text = '单位';
              color = 'green';
            } else if (params.row.visibility === 'private' || params.row.visibility === '0') {
              text = '个人';
              color = '#f02828';
            } else if (params.row.visibility === 'public' || params.row.visibility === '2') {
              text = '系统';
              color = '#2f70ff';
            }
            return h(
              'span',
              {
                style: {
                  color: color
                }
              },
              text
            );
          }
        },
        {
          title: '试卷使用次数',
          key: 'count',
          tooltip: true,
          width: 50,
          minWidth:50,
        },
        {
          title: '分数',
          key: 'totalScore',
          tooltip: true,
          width: 68,
          minWidth:50,
        },
        {
          title: '进阶考试',
          key: 'advanced',
          tooltip: true,
          width: 30,
          minWidth:50,
          render: (h, params) => {
            let advanced = params.row.advanced;
            return h(
              'span',
              {
                style: {
                  color: advanced ? 'var(--status-yes)' : 'var(--status-no)'
                }
              },
              advanced ? '是' : '否'
            );
          }
        },
        {
          title: '考试时长',
          key: 'duration',
          tooltip: true,
          width: 68,
          minWidth:50,
          render: (h, params) => {
            return h('span', `${params.row.duration ? params.row.duration : 60}分钟`);
          }
        },
        {
          title: '自测',
          key: 'type',
          ellipsis: true,
          width: 68,
          minWidth:50,
          render: (h, params) => {
            let isSelfTest = params.row.type === 'self';
            return h(
              'span',
              {
                style: {
                  color: isSelfTest ? 'var(--status-yes)' : 'var(--status-no)'
                }
              },
              isSelfTest ? '是' : '否'
            );
          }
        },
        {
          title: '试卷类型',
          key: 'paperType',
          tooltip: true,
          width: 68,
          minWidth:50,
          render: (h, params) => {
            let paperType =
              params.row.paperType == 'null' ||
              !params.row.paperType ||
              params.row.paperType == 'paper_fixed'
                ? '固定试卷'
                : params.row.paperType == 'paper_reordering'
                ? '变序试卷'
                : '随机试卷';
            return h('span', paperType);
          }
        },
        {
          title: '描述',
          key: 'description',
          ellipsis: true,
          tooltip: true,
          width: 300,
          minWidth:50,
        },
        {
          title: '创建者',
          key: 'creatorName',
          tooltip: true,
          width: 68,
          minWidth:50,
        },
        {
          title: '创建时间',
          key: 'created',
          tooltip: true,
          minWidth:50,
        },
        {
          title: '操作',
          width: 160,
          placement: 'top-right',
          action: true,
          slot:'action',
          opList:[
	          {
              txt:'预览',
              disabled:(data)=>{
                return data.paperType == 'paper_random'
              },
              on:{
                click:(data,e) => {
                  this.addTestPaper(data, 'preview');
                }
              }
            },
            {
              txt:'修改',
              disabled:(data) => {
                return this.setReBtnStatus(data)
              },
              on:{
                click:(data,e) => {
                  this.addTestPaper(data, 'modify');
                }
              }
            },
            {
              txt: '删除',
              tooltip: true,
              type: 'delete',
              title: '确定要删除这个文件吗？',
              disabled: (data) => {
                return this.setReBtnStatus(data)
              },
              on: {
                click: (data,e) => {
                  this.deleteTestPaper(data.paperId);
                }
              }
            }
          ]
        },
          {
          title: '操作',
          width: 140,
          placement: 'top-right',
          action: true,
          slot:'action1',
          show:false,
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'text',
                    size: 'small',
                    disabled: params.row.paperType == 'paper_random'
                  },
                  style: {
                    //marginRight: '5px',
                    background: 'none',
                    border: 'none',
                    boxShadow: 'none'
                  },
                  on: {
                    click: () => {
                      this.addTestPaper(params.row, 'preview');
                    }
                  }
                },
                [
                  h('img', {
                    attrs: {
                      src: require('../../../assets/project/magnifier-h.png'),
                      title: '预览'
                    },
                    style: {
                      cursor: 'pointer',
                      'margin-right': '5px',
                      'vertical-align': 'middle',
                      //width:'16px',
                      //height:'16px',
                      display: 'inline-block'
                    }
                  }),
                  h('span', {
                    style: {
                      cursor: 'pointer',
                      color: '#2f70ff'
                    }
                  })
                ]
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'text',
                    size: 'small',
                    disabled: this.setReBtnStatus(params.row)
                  },
                  style: {
                    //marginRight: '5px',
                    background: 'none',
                    border: 'none',
                    boxShadow: 'none'
                  },
                  on: {
                    click: () => {
                      this.addTestPaper(params.row, 'modify');
                    }
                  }
                },
                [
                  h('img', {
                    attrs: {
                      src: !this.setReBtnStatus(params.row)
                        ? require('../../../assets/project/modifys-h.png')
                        : require('../../../assets/project/modifys.png'),
                      title: '修改'
                    },
                    style: {
                      cursor: 'pointer',
                      'margin-right': '5px',
                      'vertical-align': 'middle',
                      //width:'16px',
                      //height:'16px',
                      display: 'inline-block',
                      marginBottom: '4px'
                    }
                  }),
                  h('span', {
                    style: {
                      cursor: 'pointer',
                      color: !this.setReBtnStatus(params.row) ? '#2d8cf0' : '#c5c8ce'
                    }
                  })
                ]
              ),
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    'ok-text': '确定',
                    'cancel-text': '取消',
                    type: 'error',
                    size: 'large',
                    title: '你确定要删除吗?',
                    transfer: true
                  },
                  style: {
                    marginLeft: '0px'
                  },
                  on: {
                    'on-ok': () => {
                      this.deleteTestPaper(params.row.paperId);
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      props: {
                        type: 'text',
                        size: 'small',
                        disabled: this.setReBtnStatus(params.row)
                      },
                      style: {
                        //marginRight: '5px',
                        background: 'none',
                        border: 'none',
                        boxShadow: 'none'
                      }
                    },
                    [
                      h('img', {
                        attrs: {
                          src: !this.setReBtnStatus(params.row)
                            ? require('../../../assets/project/delNote-h.png')
                            : require('../../../assets/project/delNote-d.png'),
                          title: '删除'
                        },
                        style: {
                          cursor: 'pointer',
                          'margin-right': '5px',
                          'vertical-align': 'middle',
                          //width:'16px',
                          //height:'16px',
                          display: 'inline-block',
                          marginBottom: '4px'
                        }
                      })
                    ]
                  )
                ]
              )
            ]);
          }
        }
      ],
      testPaperList: [], //试卷列表
      testPaperListTotal: 0, //试卷总数
      createByMe: false,
      preQuestionList: [],
      tableLoading:true
    };
  },
  computed: {},
  filters: {
    difficultyFilter: (val) => {
      let difficultyStr = '';
      if (val) {
        val = val.toLowerCase();
      }
      switch (val) {
        case 'simple':
          difficultyStr = '简单';
          break;
        case 'commonly':
          difficultyStr = '一般';
          break;
        case 'medium':
          difficultyStr = '中等';
          break;
        case 'hard':
          difficultyStr = '较难';
          break;
      }
      return difficultyStr;
    },
    modeFilter: (val) => {
      let str = '';
      if (val) {
        //			      val = val.toLowerCase();
      }
      switch (val) {
        case '1':
          str = '单选';
          break;
        case '2':
          str = '多选';
          break;
        case '3':
          str = '判断';
          break;
        case '4':
          str = '填空';
          break;
        case '5':
          str = '简答';
          break;
      }
      return str;
    },
    filterIsPublic(type) {
      //1--单位  0--个人
      let status = '';
      if (type === 1 || type === '1') {
        status = '单位';
      } else if (type === 0 || type === '0') {
        status = '个人';
      }
      return status;
    }
  },
  watch: {},
  methods: {
    handleExport() {
      downloadPDF(this.$refs.pdf, this.paperName);
    },
    // 设置高度高度有bug，分页的 条/页 只支撑10，20 ，其他的不显示
    setStyle: debounce(function() {
      // window.fullHeight = document.documentElement.clientHeight;
      // window.fullWidth = document.documentElement.clientWidth;
      // this.fullHeight = window.fullHeight;
      // this.fullWidth = window.fullWidth;
      // this.setTableHei = this.fullHeight - 197;
      // this.query.pageSize = Math.floor(this.setTableHei / 96);
      // if (this.testPaperListTotal > this.query.pageSize) {
      //   let maxPage = Math.ceil(this.testPaperListTotal / this.query.pageSize);
      //   if (maxPage < this.query.pageIndex) {
      //     this.query.pageIndex = maxPage;
      //   }
      // }
      this.queryTestPaperList();
    }, 500),
    refreshTestPaperList() {
      this.createByMe = false;
      this.testPaper.paperName = '';
      this.testPaper.visibility = '';
      this.testPaper.type = '';
      // this.testPaper.type = 1;
      this.testPaper.difficulty = '';
      this.testPaper.advanced = '';
      this.query.pageIndex = 1;
      this.queryTestPaperList();
    },
    queryTestPaperList() {
      this.tableLoading = true
      //查询试卷列表
      let _this = this;
      let params = JSON.parse(JSON.stringify(_this.testPaper));
      if (_this.createByMe) {
        params.creator = this.USER_ID;
        params.self = 1;
      }
      if (params.advanced) {
        // advanced不为空字符串时，需要解析
        params.advanced = params.advanced === '1';
      } else {
        delete params.advanced;
      }
      //查询条件存储
      this.queryObj = JSON.stringify(params);
      queryTestPaperList(params, this.query)
        .then((data) => {
          if (data.code === 1) {
            _this.testPaperList = data.data.items;
            let ids = this.testPaperList.map(item => {
              return item.paperId;
            })
            this.paperGetUsedTimes(ids)
            _this.testPaperListTotal = Number(data.data.total);
            if (_this.testPaperList.length <= 0) {
              _this.showDefImg = true;
              _this.showDefText = '暂无信息';
            } else {
              _this.showDefImg = false;
            }
          } else {
            _this.showDefImg = true;
            _this.showDefText = '暂无信息';
            _this.$Message.error(data.message);
            _this.testPaperList = [];
            _this.testPaperListTotal = 0;
          }
          this.tableLoading = false
        })
        .catch((error) => {
          console.log(error);
          _this.testPaperList = [];
          _this.testPaperListTotal = 0;
          this.tableLoading = false
        });
    },
    paperGetUsedTimes (data) {
      paperGetUsedTimes(data).then(res => {
        if (res.code == 1) {
          let list = res.data
          this.testPaperList.forEach((item, index) => {
            // 数组中查找具有相同 paperId 的元素
            const obj = list.find(item2 => item2.paperId === item.paperId);
            if (obj) {
               this.$set(item,'count',obj.count)
            }
          })
        } else {
          this.$Message.warning(res.message)
        }
      })
    },
    addTestPaper(obj, type) {
      //添加/修改/预览试卷
      this.paperName = obj.paperName;
      this.totalScore = 0;
      if (type == 'add') {
        this.$router.push({
          name: 'testPaperDetail'
        });
      } else if (type == 'modify') {
        sessionStorage.setItem('queryObj', this.queryObj);
        this.$router.push({
          name: 'testPaperDetail',
          query: {
            id: obj.paperId
          }
        });
      } else if (type == 'preview') {
        this.preQuestionList = [];
        this.previewModal.show = true;
        this.previewIndex = 0;
        this.previewModal.loading = true;
        queryTestPaperQuestionList({
          paperId: obj.paperId
        })
          .then((data) => {
            if (data.code == 1) {
              let questionInfoList = data.data.paperQuestion;
              questionInfoList.forEach((item) => {
                let questionType = item.questionType.toString();
                let isObjectiveQuestion = ['1', '2', '3', '5', '6'].includes(questionType);
                let isCtfQuestion = ['4'].includes(questionType);
                item.answerResult = item.showRight;
                item.explanation = item.description;
                if (questionType == '4') {
                  item.modeCode = '6'; //与题目的modeCode对应上:1-单选、2-多选、3-判断、4-填空、5-简答
                } else if (questionType == '5') {
                  item.modeCode = '4'; //与题目的modeCode对应上:1-单选、2-多选、3-判断、4-填空、5-简答
                } else if (questionType == '6') {
                  item.modeCode = '5'; //与题目的modeCode对应上:1-单选、2-多选、3-判断、4-填空、5-简答
                } else {
                  item.modeCode = questionType;
                }
              });
              this.preQuestionList = questionInfoList;
            } else {
              this.$Message.error(data.message);
            }
            this.previewModal.loading = false;
          })
          .catch((error) => {
            this.previewModal.loading = false;
          });
      }
    },
    parseDescription(question) {
      if (!question.answers) {
        return;
      }
      let description;
      description = question.name.replace(
        /\{\{.*?\}\}/g,
        `<span class='quesBlank' disabled style='width:40px;padding:0px 5px;outline:none;box-shadow:none;border:none;border-bottom:1px solid rgb(168,166,200);color:#2d8cf0'></span>`
      );
      let el = document.createElement('div');
      el.innerHTML = description;
      let answersEle = el.getElementsByClassName('quesBlank');
      Array.from(answersEle).forEach((ele, index) => {
        answersEle[index].innerHTML = question.answers[index].explanation;
      });
      return el.innerHTML;
    },
    deleteTestPaper(id) {
      let _this = this;
      delTestPaper({
        paperId: id
      }).then((data) => {
        if (data.code === 1) {
          _this.$Message.info('删除成功');
          this.query.pageIndex =
            this.testPaperList.length == 1 && this.query.pageIndex > 1
              ? this.query.pageIndex - 1
              : this.query.pageIndex;
          _this.queryTestPaperList();
        } else {
          _this.$Message.error(data.message);
        }
      });
    },
    changePage: debounce(function(val) {
      this.query.pageIndex = val;
      this.queryTestPaperList();
    }, 500),
    // 按钮点击状态
    setReBtnStatus(params) {
      let userid = params.creator;
      if (params.visibility != 'public' && (userid === this.USER_ID || this.isRootDesigner)) {
        return false;
      } else {
        return true;
      }
    }
  },
  mounted() {
    //赋值查询条件
    let queryObj = sessionStorage.getItem('queryObj');
    if (queryObj) {
      let params = JSON.parse(queryObj);
      this.createByMe = params.creator == this.USER_ID;
      this.testPaper = params;
      sessionStorage.removeItem('queryObj');
    }
    this.setStyle();
    // window.onresize = () => {
    //   this.setStyle();
    // };
  },
  beforeDestroy() {
    window.onresize = null;
  },
  created() {}
};
</script>
<style>
::-webkit-scrollbar {
  width: 5px;
  /*滚动条宽度*/
  height: 5px;
  /*滚动条高度*/
}
/*定义滚动条轨道 内阴影+圆角*/

::-webkit-scrollbar-track {
  border-radius: 2.5px;
  /*滚动条的背景区域的圆角*/
  background-color: #e6e6e6;
  /*滚动条的背景颜色*/
}
/*定义滑块 内阴影+圆角*/

::-webkit-scrollbar-thumb {
  border-radius: 2.5px;
  /*滚动条的圆角*/
  background-color: #aaa;
  /*滚动条的背景颜色*/
}

#testPaper .fixedHeightTable .ivu-table-body {
  max-height: calc(100vh - 345px);
  overflow: hidden auto;
  overscroll-behavior: contain;
}

#previewModal .ivu-modal-body {
  max-height: calc(100vh - 252px);
  overflow: hidden auto;
}
</style>

